<?php
define('ROOT_DIR', $_SERVER['DOCUMENT_ROOT'].'/');
function get_answer_notrg($app_key, $app_secret, $ques1, $ques2, $fzpoint) {
    $timestamp = strval(time());
    $sign_content = $app_key . $app_secret . $timestamp;
    $sign_result = md5($sign_content);
    $headers = array(
        "app_key: $app_key",
        "timestamp: $timestamp",
        "sign: $sign_result",
        "Content-Type: application/json",
    );
    $data = json_encode(array(
        "messages" => array(
            array(
                "role" => "user",
                "content" => "问题：" . $ques1 . "
                用户答案：" . $ques2 . "
                请给用户答案打分(" . $fzpoint . "分)!答案为json格式,score+comment"
            )
        ),
        "intent" => "chat"
    ));
    $ch = curl_init('https://api-maas.singularity-ai.com/sky-work/api/v1/chat');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    $info = curl_getinfo($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) {
        echo "cURL Error: $error";
    } else {
        $ld = array();
        $ansewe = '';
        $lines = explode('data:', $response);
        foreach ($lines as $line) {
            if (trim($line)) {
                $data = json_decode($line, true);
                if (isset($data['arguments'][0]['messages'])) {
                    $messages = $data['arguments'][0]['messages'];
                    foreach ($messages as $message) {
                        $ld[] = $message['text'];
                    }
                }
            }
        }
        foreach ($ld as $i) {
            if ($i != '') {
                $ansewe .= $i . "\n";
            }
        }
        echo json_encode(array('code'=>200,'data'=>$ansewe));
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require('../../setting.php');
    $quest_parm1 = $_POST['param1'];
    $quest_parm2 = $_POST['param2'];
    $fzpoint = $_POST['param3'];
    $userid = $_POST['param4'];
    if($index_array['ai_open'] == 'open'){
        require(ROOT_DIR.'cofd/common.php');
        $sql = "SELECT vip FROM exam_user WHERE id=$userid";
        $res = $conn->query($sql);
        $row = $res->fetch_assoc();
        if(strtotime($row['vip']) > time()){
            get_answer_notrg($ai_array['ai_key'], $ai_array['ai_secret'], $quest_parm1, $quest_parm2, $fzpoint);   
            $conn->close();
            exit();
        }else{
            echo json_encode(array('code'=>201,'data'=>'非VIP禁止使用AI功能'));
            $conn->close();
            exit();
        }
    }
    $aikey = $ai_array['ai_key'];
    $aisecert = $ai_array['ai_secret'];
    get_answer_notrg($aikey, $aisecert, $quest_parm1, $quest_parm2, $fzpoint);   
}
?>